package com.cn.controller.admin;

import com.cn.enums.ErrorMsg;
import com.cn.entity.Admin;
import com.cn.service.AdminService;
import com.cn.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * 管理员认证相关控制器
 * 处理管理员登录、登出、管理员列表、添加管理员等功能
 */
@RestController
@RequestMapping("admin/auth")
public class AdminAuthController {

    @Autowired
    private AdminService adminService;

    @GetMapping("login")
    public Result login(@RequestParam("accountNumber") String accountNumber,
                        @RequestParam("adminPassword") String adminPassword,
                        HttpSession session){
        // 参数校验
        if (accountNumber == null || accountNumber.trim().isEmpty()) {
            return Result.fail(ErrorMsg.PARAM_ERROR);
        }
        if (adminPassword == null || adminPassword.trim().isEmpty()) {
            return Result.fail(ErrorMsg.PARAM_ERROR);
        }
        
        Admin admin =adminService.login(accountNumber,adminPassword);
        if (null == admin) {
            return Result.fail(ErrorMsg.EMAIL_LOGIN_ERROR);
        }
        session.setAttribute("admin", admin);
        return Result.success(admin);
    }

    @GetMapping("loginOut")
    public Result loginOut(HttpSession session){
        session.removeAttribute("admin");
        return Result.success();
    }

    @GetMapping("list")
    public Result getAdminList(HttpSession session,
                               @RequestParam(value = "page",required = false) Integer page,
                               @RequestParam(value = "nums",required = false) Integer nums){
        if(session.getAttribute("admin")==null){
            return Result.fail(ErrorMsg.COOKIE_ERROR);
        }
        int p=1;
        int n=8;
        if(null!=page){
            p=page>0?page:1;
        }
        if(null!=nums){
            n=nums>0?nums:8;
        }
        return Result.success(adminService.getAdminList(p,n));
    }

    @PostMapping("add")
    public Result addAdmin(HttpSession session,
                           @RequestBody Admin admin){
        if(session.getAttribute("admin")==null){
            return Result.fail(ErrorMsg.COOKIE_ERROR);
        }
        if(adminService.addAdmin(admin)){
            return Result.success();
        }
        return Result.fail(ErrorMsg.PARAM_ERROR);
    }
}